package github.sf.fw.tools.db.sql;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.builder.impl.SQLDeleteBuilderImpl;
import com.alibaba.druid.sql.builder.impl.SQLUpdateBuilderImpl;
import github.sf.fw.utils.SQLFilter;

import java.util.Map;

/**
 * SqlBuilder
 *
 * @author zhoup
 * @since 2023/4/21
 */
public class SqlBuilder {
    private final DbType dbType = DbType.mysql;

    public enum Operation {
        Update, Insert, Delete, Query
    }


    public String buildSql(Operation type, String tableName, Map<String, Object> data, Map<String, Object> condition) {
        switch (type) {
            case Update:
                return update(tableName, data, condition);
            case Delete:
                return delete(tableName, condition);
            case Insert:
                return insert(tableName, data);
        }
        throw new UnsupportedOperationException("暂不支持" + type.name() + "类型");
    }

    public String update(String tableName, Map<String, Object> data, Map<String, Object> condition) {
        SQLUpdateBuilderImpl sqlUpdateBuilder = new SQLUpdateBuilderImpl(dbType);
        sqlUpdateBuilder.from(tableName);
        sqlUpdateBuilder.setValue(data);
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            sqlUpdateBuilder.whereAnd(condEq(entry.getKey(), entry.getValue()));
        }
//        sqlUpdateBuilder.limit(1);
        return sqlUpdateBuilder.toString();
    }

    private String condEq(String key, Object value) {
        return SQLFilter.filter(key) + "= '" + SQLFilter.filter(value.toString()) + "'";
    }

    public String delete(String tableName, Map<String, Object> condition) {
        SQLDeleteBuilderImpl deleteBuilder = new SQLDeleteBuilderImpl(dbType);
        deleteBuilder.from(tableName);
        for (Map.Entry<String, Object> entry : condition.entrySet()) {
            deleteBuilder.whereAnd(condEq(entry.getKey(), entry.getValue()));
        }
//        deleteBuilder.limit(1);
        return deleteBuilder.toString();
    }

    public String deleteById(String tableName, String idPropertyName, String idValue) {
        SQLDeleteBuilderImpl deleteBuilder = new SQLDeleteBuilderImpl(dbType);
        deleteBuilder.from(tableName);
        deleteBuilder.where(condEq(idPropertyName, idValue));
        return deleteBuilder.toString();
    }

    public String insert(String tableName, Map<String, Object> data) {
        SQLInsertBuilder sqlInsertBuilder = new SQLInsertBuilder(dbType);
        sqlInsertBuilder.from(tableName);
        sqlInsertBuilder.value(data);
        return sqlInsertBuilder.getSQL();
    }
}
